/**
 * 
 */
package com.et114.components.acegi.intercept.web;

import org.acegisecurity.Authentication;
import org.acegisecurity.ui.webapp.AuthenticationProcessingFilter;
import org.acegisecurity.AuthenticationException;

import javax.servlet.http.HttpServletRequest;

import java.util.*;

/**
 * @author guanhw
 */
public class ValidCodeAuthenticationProcessingFilter extends AuthenticationProcessingFilter {
	public static final String	ACEGI_SECURITY_FORM_VALIDCODE_KEY	= "j_valid_code";
	public static final String  ACEGI_SECURITY_SUCCESS_URL_METHOD = "j_success_to" ;
	public String authCode = ACEGI_SECURITY_FORM_VALIDCODE_KEY ;
	private Map targetUrls; 
	private boolean validCode = true ; 
	//
	public static final String  ACEGI_SECURITY_VALIDKEY = "____ISVALID_" ; 
	public static final String  ACEGI_SECURITY_VALID_VALUE = "CHECKED_SUCCESS_" ; 
	
	public Authentication attemptAuthentication (	HttpServletRequest httpServletRequest ) throws AuthenticationException {
		doValidCode( httpServletRequest ) ;
		return super.attemptAuthentication ( httpServletRequest );
	}
	
	public void doValidCode (	HttpServletRequest httpServletRequest ) throws AuthenticationException {
		Object obj = httpServletRequest.getSession ( ).getAttribute ( ACEGI_SECURITY_VALIDKEY ) ;
		if ( validCode ) {
			if ( !ACEGI_SECURITY_VALID_VALUE.equals (  obj )  ) {
				String inputValidationCode = obtainValidCode( httpServletRequest );
				String ssnValidationCode = ( String ) httpServletRequest.getSession ( ).getAttribute ( authCode );
				if ( inputValidationCode == null || "".equals ( inputValidationCode.trim ( ) ) ) 
					throw new ValidCodeException( "" ) ; 
				if ( ssnValidationCode != null	&& ! ssnValidationCode.equals ( inputValidationCode ) ) 
					throw new ValidCodeException( ""   ) ; 
			}						
		}
	}	
	
	protected String obtainValidCode ( HttpServletRequest request ) {
		return request.getParameter ( authCode );
	}

	public String getAuthCode ( ) {
		return authCode;
	}

	public void setAuthCode ( String authCode ) {
		if ( authCode != null ) 
			this.authCode = authCode ;
	}

	public Map getTargetUrls ( ) {
		return targetUrls;
	}

	public void setTargetUrls ( Map targetUrls ) {
		this.targetUrls = targetUrls;
	}

	public boolean setValidCode ( ) {
		return validCode;
	}

	public void setValidCode ( boolean validCode ) {
		this.validCode = validCode;
	}

}
